import socket

from op_drf.response import SuccessResponse
from .handler import set_password
from .models import *
from op_drf.serializers import CustomModelSerializer
from rest_framework import serializers
from loguru import logger
from datetime import datetime


class ReadStarUserSerializer(CustomModelSerializer):

    class Meta:
        model = StarUser
        # fields = "__all__"
        fields = ["id","username"]


class WriteStarUserSerializer(CustomModelSerializer):
    username = serializers.CharField(max_length=20,required=True)
    pwd = serializers.CharField(max_length=100,required=True)

    def create(self, validated_data):
        username = validated_data.get("username",None)

        users =StarUser.objects.filter(is_delete=False,is_active=True,username=username)
        if users:
            user_obj = users[0]
            return user_obj
        else:
            instance = super().create(validated_data)
            return instance

    class Meta:
        model = StarUser
        # fields = "__all__"
        fields = ["id","username","pwd"]


class ReadLoginHistorySerializer(CustomModelSerializer):
    user_id = serializers.SerializerMethodField(read_only=True)

    def get_user_id(self, obj):
        return int(obj.user.pk) if obj.user else 0
    class Meta:
        model = LoginHistory
        # fields = "__all__"
        fields = ["id","username","user_id"]

class WriteLoginHistorySerializer(CustomModelSerializer):
    username = serializers.CharField(max_length=20,required=True)
    pwd = serializers.CharField(max_length=100,required=True)
    logintime = serializers.DateTimeField(default=datetime.now())
    loginstatus = serializers.BooleanField(default=True)

    def create(self, validated_data):
        username = validated_data.get("username",None)
        validated_data["loginnum"] = validated_data["username"] + datetime.now().strftime("%Y%m%d%H%M%S")

        users =StarUser.objects.filter(is_delete=False,is_active=True,username=username)
        if users:
            user_obj = users[0]
            pwd = validated_data.get("pwd",None)

            if user_obj.pwd == set_password(pwd):
                validated_data["pwd"]=set_password(pwd)
                instance = super().create(validated_data)
                instance.user = user_obj
                instance.save()
                return instance
        else:

            instance = super().create(validated_data)
            loginnum = instance.username+datetime.now().strftime("%Y%m%d%H%M%S")
            logger.debug(loginnum)
            instance.loginnum = loginnum
            instance.save()
            return instance

    class Meta:
        model = LoginHistory
        fields = "__all__"